package com.socialsoftware.repository;

import android.app.Application;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socialsoftware.api.ApiService;
import com.socialsoftware.model.AppDatabase;
import com.socialsoftware.model.FriendRequest;
import com.socialsoftware.model.FriendRequestDao;
import com.socialsoftware.util.SessionManager;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 好友请求数据仓库
 * 用于处理好友请求的数据操作，包括本地数据库和远程API
 */
public class FriendRequestRepository {
    private static final String TAG = "FriendRequestRepository";
    
    private final FriendRequestDao friendRequestDao;
    private final SessionManager sessionManager;
    private final ApiService apiService;
    private final OkHttpClient client;
    
    public FriendRequestRepository(Application application) {
        AppDatabase db = AppDatabase.getDatabase(application);
        friendRequestDao = db.friendRequestDao();
        sessionManager = SessionManager.getInstance(application);
        apiService = new ApiService(sessionManager);
        client = apiService.getHttpClient();
    }
    
    /**
     * 获取当前用户的待处理好友请求
     */
    public LiveData<List<FriendRequest>> getPendingRequests() {
        Long currentUserId = sessionManager.getCurrentUserId();
        if (currentUserId == null) {
            Log.e(TAG, "获取当前用户ID失败");
            return getEmptyFriendRequestList();
        }
        return friendRequestDao.getPendingRequestsForUser(currentUserId);
    }
    
    /**
     * 获取当前用户的所有好友请求
     */
    public LiveData<List<FriendRequest>> getAllRequests() {
        Long currentUserId = sessionManager.getCurrentUserId();
        if (currentUserId == null) {
            Log.e(TAG, "获取当前用户ID失败");
            return getEmptyFriendRequestList();
        }
        return friendRequestDao.getAllRequestsForUser(currentUserId);
    }
    
    /**
     * 获取待处理好友请求数量
     */
    public LiveData<Integer> getPendingRequestsCount() {
        Long currentUserId = sessionManager.getCurrentUserId();
        if (currentUserId == null) {
            Log.e(TAG, "获取当前用户ID失败");
            return getZeroCount();
        }
        return friendRequestDao.getPendingRequestsCount(currentUserId);
    }
    
    /**
     * 返回空的好友请求列表LiveData
     */
    private LiveData<List<FriendRequest>> getEmptyFriendRequestList() {
        MutableLiveData<List<FriendRequest>> emptyList = new MutableLiveData<>();
        emptyList.setValue(new ArrayList<>());
        return emptyList;
    }
    
    /**
     * 返回值为0的计数LiveData
     */
    private LiveData<Integer> getZeroCount() {
        MutableLiveData<Integer> zeroCount = new MutableLiveData<>();
        zeroCount.setValue(0);
        return zeroCount;
    }
    
    /**
     * 从服务器获取待处理好友请求
     */
    public void fetchPendingRequestsFromServer() {
        // 检查是否已登录
        if (!sessionManager.isLoggedIn()) {
            Log.e(TAG, "用户未登录，无法获取好友请求");
            return;
        }
        
        String token = sessionManager.getAuthToken();
        if (token == null || token.isEmpty()) {
            Log.e(TAG, "无效的认证令牌");
            return;
        }
        
        Long currentUserId = sessionManager.getCurrentUserId();
        if (currentUserId == null) {
            Log.e(TAG, "无法获取当前用户ID");
            return;
        }
        
        Log.d(TAG, "开始从服务器获取用户ID: " + currentUserId + " 的待处理好友请求");
        
        // 构建API请求
        String url = apiService.getCurrentBaseUrl() + "/api/friendships/pending/current";
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "Bearer " + token)
                .build();
        
        // 发送异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "获取好友请求失败: " + e.getMessage(), e);
                Log.d(TAG, "尝试从本地数据库加载缓存的好友请求");
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    Log.e(TAG, "获取好友请求失败: HTTP " + response.code() + " - " + response.message());
                    return;
                }
                
                String responseBody = response.body().string();
                Log.d(TAG, "好友请求响应成功，开始处理数据");
                
                try {
                    // 解析JSON响应
                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<Map<String, Object>>>(){}.getType();
                    List<Map<String, Object>> requestsData = gson.fromJson(responseBody, listType);
                    
                    Log.d(TAG, "从服务器获取到 " + requestsData.size() + " 条好友请求");
                    
                    // 转换为FriendRequest对象
                    List<FriendRequest> friendRequests = new ArrayList<>();
                    for (Map<String, Object> data : requestsData) {
                        FriendRequest request = parseFriendRequest(data);
                        if (request != null) {
                            // 确保设置了接收者ID（当前用户）
                            if (request.getAddresseeId() == null) {
                                request.setAddresseeId(currentUserId);
                            }
                            friendRequests.add(request);
                            Log.d(TAG, "解析好友请求: ID=" + request.getId() + 
                                    ", 发送者=" + request.getRequesterName() + 
                                    ", 状态=" + request.getStatus());
                        }
                    }
                    
                    // 保存到本地数据库
                    if (!friendRequests.isEmpty()) {
                        AppDatabase.databaseWriteExecutor.execute(() -> {
                            // 先清除当前用户的所有待处理请求，避免重复
                            friendRequestDao.deleteAllPendingRequestsForUser(currentUserId);
                            
                            // 插入新的请求
                            friendRequestDao.insertAll(friendRequests);
                            Log.d(TAG, "成功保存 " + friendRequests.size() + " 条好友请求到本地数据库");
                        });
                    } else {
                        Log.d(TAG, "没有新的好友请求需要保存");
                        // 清除旧的请求
                        AppDatabase.databaseWriteExecutor.execute(() -> {
                            friendRequestDao.deleteAllPendingRequestsForUser(currentUserId);
                        });
                    }
                } catch (Exception e) {
                    Log.e(TAG, "解析好友请求数据失败: " + e.getMessage(), e);
                }
            }
        });
    }
    
    /**
     * 接受好友请求
     */
    public void acceptFriendRequest(FriendRequest friendRequest, final Callback callback) {
        String url = apiService.getCurrentBaseUrl() + "/api/friendships/" + friendRequest.getId() + "/accept";
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "Bearer " + sessionManager.getAuthToken())
                .post(okhttp3.internal.Util.EMPTY_REQUEST)
                .build();
        
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "接受好友请求失败: " + e.getMessage(), e);
                if (callback != null) {
                    callback.onFailure(call, e);
                }
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 更新本地数据库
                    AppDatabase.databaseWriteExecutor.execute(() -> {
                        friendRequestDao.updateStatus(friendRequest.getId(), "ACCEPTED", new Date().getTime());
                    });
                    Log.d(TAG, "好友请求已接受: " + friendRequest.getId());
                } else {
                    Log.e(TAG, "接受好友请求失败: " + response.code());
                }
                
                if (callback != null) {
                    callback.onResponse(call, response);
                }
            }
        });
    }
    
    /**
     * 拒绝好友请求
     */
    public void rejectFriendRequest(FriendRequest friendRequest, final Callback callback) {
        String url = apiService.getCurrentBaseUrl() + "/api/friendships/" + friendRequest.getId() + "/reject";
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "Bearer " + sessionManager.getAuthToken())
                .post(okhttp3.internal.Util.EMPTY_REQUEST)
                .build();
        
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "拒绝好友请求失败: " + e.getMessage(), e);
                if (callback != null) {
                    callback.onFailure(call, e);
                }
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 更新本地数据库
                    AppDatabase.databaseWriteExecutor.execute(() -> {
                        friendRequestDao.updateStatus(friendRequest.getId(), "REJECTED", new Date().getTime());
                    });
                    Log.d(TAG, "好友请求已拒绝: " + friendRequest.getId());
                } else {
                    Log.e(TAG, "拒绝好友请求失败: " + response.code());
                }
                
                if (callback != null) {
                    callback.onResponse(call, response);
                }
            }
        });
    }
    
    /**
     * 拉黑用户
     */
    public void blockUser(Long userId, final Callback callback) {
        // 在本地数据库中拉黑用户
        AppDatabase.databaseWriteExecutor.execute(() -> {
            // 获取该用户发送的所有请求
            Long currentUserId = sessionManager.getCurrentUserId();
            if (currentUserId != null) {
                List<FriendRequest> requests = friendRequestDao.getPendingRequestsForUserSync(currentUserId);
                for (FriendRequest request : requests) {
                    if (request.getRequesterId() != null && request.getRequesterId().equals(userId)) {
                        friendRequestDao.updateStatus(request.getId(), "BLOCKED", new Date().getTime());
                    }
                }
            } else {
                Log.e(TAG, "拉黑用户失败: 无法获取当前用户ID");
            }
        });
        
        // 尝试通过API拉黑用户
        String url = apiService.getCurrentBaseUrl() + "/api/users/" + userId + "/block";
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "Bearer " + sessionManager.getAuthToken())
                .post(okhttp3.internal.Util.EMPTY_REQUEST)
                .build();
        
        client.newCall(request).enqueue(callback);
    }
    
    /**
     * 解析服务器返回的好友请求数据
     */
    private FriendRequest parseFriendRequest(Map<String, Object> data) {
        try {
            FriendRequest friendRequest = new FriendRequest();
            
            // 设置基本信息
            if (data.containsKey("id")) {
                Object idObj = data.get("id");
                if (idObj instanceof Number) {
                    friendRequest.setId(((Number)idObj).longValue());
                } else {
                    friendRequest.setId(Long.valueOf(idObj.toString()));
                }
            }
            
            // 设置状态
            if (data.containsKey("status")) {
                friendRequest.setStatus(data.get("status").toString());
            } else {
                friendRequest.setStatus("PENDING");
            }
            
            // 设置请求备注
            if (data.containsKey("requesterNote")) {
                friendRequest.setRequesterNote(data.get("requesterNote").toString());
            }
            
            // 设置时间信息 - 处理不同格式的日期
            if (data.containsKey("createdAt")) {
                Object createdAtObj = data.get("createdAt");
                try {
                    if (createdAtObj instanceof Number) {
                        // 如果是数字类型（时间戳）
                        friendRequest.setCreatedAt(new Date(((Number)createdAtObj).longValue()));
                    } else if (createdAtObj instanceof String) {
                        String createdAtStr = (String)createdAtObj;
                        // 尝试解析为长整型（时间戳）
                        try {
                            long timestamp = Long.parseLong(createdAtStr);
                            friendRequest.setCreatedAt(new Date(timestamp));
                        } catch (NumberFormatException e) {
                            // 如果不是数字，尝试解析为ISO日期格式
                            try {
                                // 简单处理，实际应用中可能需要更复杂的日期解析
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
                                format.setTimeZone(TimeZone.getTimeZone("UTC"));
                                friendRequest.setCreatedAt(format.parse(createdAtStr));
                            } catch (Exception e2) {
                                // 如果所有解析都失败，使用当前时间
                                Log.w(TAG, "无法解析创建时间: " + createdAtStr, e2);
                                friendRequest.setCreatedAt(new Date());
                            }
                        }
                    } else {
                        // 其他类型，使用当前时间
                        friendRequest.setCreatedAt(new Date());
                    }
                } catch (Exception e) {
                    Log.w(TAG, "解析创建时间时出错", e);
                    friendRequest.setCreatedAt(new Date());
                }
            } else {
                friendRequest.setCreatedAt(new Date());
            }
            
            // 类似地处理updatedAt
            if (data.containsKey("updatedAt")) {
                Object updatedAtObj = data.get("updatedAt");
                try {
                    if (updatedAtObj instanceof Number) {
                        friendRequest.setUpdatedAt(new Date(((Number)updatedAtObj).longValue()));
                    } else if (updatedAtObj instanceof String) {
                        String updatedAtStr = (String)updatedAtObj;
                        try {
                            long timestamp = Long.parseLong(updatedAtStr);
                            friendRequest.setUpdatedAt(new Date(timestamp));
                        } catch (NumberFormatException e) {
                            try {
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
                                format.setTimeZone(TimeZone.getTimeZone("UTC"));
                                friendRequest.setUpdatedAt(format.parse(updatedAtStr));
                            } catch (Exception e2) {
                                friendRequest.setUpdatedAt(new Date());
                            }
                        }
                    } else {
                        friendRequest.setUpdatedAt(new Date());
                    }
                } catch (Exception e) {
                    friendRequest.setUpdatedAt(new Date());
                }
            } else {
                friendRequest.setUpdatedAt(new Date());
            }
            
            // 设置请求者信息
            if (data.containsKey("requester")) {
                Object requesterObj = data.get("requester");
                Map<String, Object> requester;
                
                if (requesterObj instanceof Map) {
                    requester = (Map<String, Object>) requesterObj;
                    
                    // 处理ID
                    if (requester.containsKey("id")) {
                        Object idObj = requester.get("id");
                        if (idObj instanceof Number) {
                            friendRequest.setRequesterId(((Number)idObj).longValue());
                        } else {
                            try {
                                friendRequest.setRequesterId(Long.valueOf(idObj.toString()));
                            } catch (NumberFormatException e) {
                                Log.w(TAG, "无法解析请求者ID: " + idObj, e);
                            }
                        }
                    }
                    
                    // 处理名称
                    if (requester.containsKey("fullName")) {
                        friendRequest.setRequesterName(requester.get("fullName").toString());
                    } else if (requester.containsKey("username")) {
                        friendRequest.setRequesterName(requester.get("username").toString());
                    } else if (requester.containsKey("name")) {
                        friendRequest.setRequesterName(requester.get("name").toString());
                    }
                    
                    // 处理头像
                    if (requester.containsKey("avatarUrl")) {
                        String avatarUrl = requester.get("avatarUrl").toString();
                        // 如果是完整URL，提取文件名作为资源名
                        if (avatarUrl.startsWith("http")) {
                            String[] parts = avatarUrl.split("/");
                            String fileName = parts[parts.length - 1];
                            // 移除文件扩展名
                            int dotIndex = fileName.lastIndexOf(".");
                            if (dotIndex > 0) {
                                fileName = fileName.substring(0, dotIndex);
                            }
                            friendRequest.setRequesterAvatar(fileName);
                        } else {
                            friendRequest.setRequesterAvatar(avatarUrl);
                        }
                    } else {
                        friendRequest.setRequesterAvatar("avatar_default");
                    }
                }
            }
            
            // 设置接收者信息
            if (data.containsKey("addressee")) {
                Object addresseeObj = data.get("addressee");
                Map<String, Object> addressee;
                
                if (addresseeObj instanceof Map) {
                    addressee = (Map<String, Object>) addresseeObj;
                    
                    // 处理ID
                    if (addressee.containsKey("id")) {
                        Object idObj = addressee.get("id");
                        if (idObj instanceof Number) {
                            friendRequest.setAddresseeId(((Number)idObj).longValue());
                        } else {
                            try {
                                friendRequest.setAddresseeId(Long.valueOf(idObj.toString()));
                            } catch (NumberFormatException e) {
                                Log.w(TAG, "无法解析接收者ID: " + idObj, e);
                            }
                        }
                    }
                    
                    // 处理名称
                    if (addressee.containsKey("fullName")) {
                        friendRequest.setAddresseeName(addressee.get("fullName").toString());
                    } else if (addressee.containsKey("username")) {
                        friendRequest.setAddresseeName(addressee.get("username").toString());
                    } else if (addressee.containsKey("name")) {
                        friendRequest.setAddresseeName(addressee.get("name").toString());
                    }
                }
            }
            
            return friendRequest;
        } catch (Exception e) {
            Log.e(TAG, "解析好友请求数据失败: " + e.getMessage(), e);
            return null;
        }
    }
}